<template>
    <div>

    </div>
</template>
<script>
  import axios from "axios";
  import md5 from 'js-md5'
  import SIdentify from "../../components/identify";
  import sIdentify from "../../components/identfiy_2"
  // function isRepeat(){
  //   var i=0;
  //   var flag=false;
  //   for (i=0;i<this.accountAll.length;i++){
  //     if(this.teacherForm.teacherAccount==this.accountAll[i].account){
  //       flag=true;
  //       break;
  //     }
  //   }
  //   return flag;
  // }
  export default {
    name: "TeacherRegister",
    components:{
      SIdentify:SIdentify,
      // identify:SIdentify
      sIdentify:sIdentify
    },

    data() {
      // function isRepeat(){
      //   var i=0;
      //   var flag=false;
      //   for (i=0;i<this.accountAll.length;i++){
      //     if(this.teacherForm.teacherAccount==this.accountAll[i].account){
      //       flag=true;
      //       break;
      //     }
      //   }
      //   return flag;
      // }
      let phoneNumber = /^(13[0-9]|17[0-9]|14[5|7] |15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
      let emailNumber = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      let password = /^[a-zA-Z]\w{5,17}$/;
      let id=/^[A-Za-z0-9]{8}$/
      var validStudentAccount= (rule, value, callback) => {
        var i=0;
        var flag=false;
        for (i=0;i<this.accountAll.length;i++){
          if(this.studentForm.studentAccount==this.accountAll[i].account){
            flag=true;
            break;
          }
        }
        if(flag ){
          callback(new Error("账号已存在"));
        }else if (phoneNumber.test(value)) {
          callback();
        } else if (emailNumber.test(value)) {
          callback();
        }
        else {
          callback(new Error("输入的邮箱/账号/手机号不合法"));
        }
      };
      var validTeacherAccount = (rule, value, callback) => {
        var i=0;
        var flag=false;
        for (i=0;i<this.accountAll.length;i++){
          if(this.teacherForm.teacherAccount==this.accountAll[i].account){
            flag=true;
            break;
          }
        }
        if(flag ){
          callback(new Error("账号已存在"));
        }else if (phoneNumber.test(value)) {
          callback();
        } else if (emailNumber.test(value)) {
          callback();
        }
        else {
          callback(new Error("输入的邮箱/账号/手机号不合法"));
        }
      };
      var validPassword = (rule, value, callback) => {
        if (password.test(value)) {
          callback();
        } else {
          callback(new Error("以字母开头，长度在6~18之间，只能包含字母、数字和下划线"))
        }
      }

      var phoneValid = (rule, value, callback) => {
        if (phoneNumber.test(value)) {
          callback();
        } else {
          callback(new Error("输入的手机号不正确"))
        }
      }
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else if (!password.test(value)) {
          callback(new Error('密码格式以字母开头，长度在6~18之间，只能包含字母、数字和下划线'))
        } else {
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.teacherForm.teacherPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else if (!password.test(value)) {
          callback(new Error('密码格式以字母开头，长度在6~18之间，只能包含字母、数字和下划线'))
        } else {
          callback();
        }
      };
      var validatePass3 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else if (!password.test(value)) {
          callback(new Error('密码格式以字母开头，长度在6~18之间，只能包含字母、数字和下划线'))
        } else {
          callback();
        }
      };
      var validatePass4 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.studentForm.studentPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else if (!password.test(value)) {
          callback(new Error('密码格式以字母开头，长度在6~18之间，只能包含字母、数字和下划线'))
        } else {
          callback();
        }
      };
      var validStudentId = (rule,value,callback) =>{
        var i=0;
        var flag=false;
        for (i=0;i<this.student.length;i++){
          if(this.studentForm.studentId==this.student[i].studentId){
            flag=true;
            break;
          }
        }
        if(flag){
          callback(new Error("学号已经存在"));
        }else if(!id.test(value)){
          callback("输入正确的八位数字和字母组成的Id");
        }else{
          callback();
        }
      };
      var validTeacherId = (rule,value,callback) =>{
        var i=0;
        var flag=false;
        for (i=0;i<this.teacher.length;i++){
          if(this.teacherForm.teacherId==this.teacher[i].teacherId){
            flag=true;
            break;
          }
        }
        if(flag){
          callback(new Error("教师号已经存在"));
        }else if(!id.test(value)){
          callback("输入正确的八位数字和字母组成的Id");
        }else{
          callback();
        }
      }
      return {
        flag:true,
        identifyTeacherCodes: "1234567890",
        identifyStudentCodes: "1234567890",
        identifyStudentCode: "",
        identifyTeacherCode:"",
        s:"",
        accountAll:[

        ],
        student:[

        ],
        teacher:[

        ],
        teacherForm: {
          teacherAccount: '',
          teacherPassword: '',
          teacherPassword2: '',
          teacherName: '',
          teacherId: '',
          college: '',
          teacherCode: '',
        },
        studentForm: {
          studentAccount: '',
          studentPassword: '',
          studentPassword2: '',
          studentName: '',
          studentId: '',
          school: '',
          studentCode: '',
        },
        rules: {
          studentAccount: [
            {required: true, message: '请输入邮箱/手机号', trigger: 'blur'},
            {validator: validStudentAccount, trigger: 'blur'},
          ],
          teacherAccount: [
            {required: true, message: '请输入邮箱/手机号', trigger: 'blur'},
            {validator: validTeacherAccount, trigger: 'blur'},
          ],
          teacherPassword: [
            {validator: validatePass, trigger: 'blur'}
          ],
          teacherPassword2: [
            {validator: validatePass2, trigger: 'blur'}
          ],
          teacherName: [
            {required: true, message: '请输入名字', trigger: 'blur'},
            {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'},
            {
              required: true,
              pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
              message: '姓名不支持特殊字符',
              trigger: 'blur'
            }
          ],
          studentName: [
            {required: true, message: '请输入名字', trigger: 'blur'},
            {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'},
            {
              required: true,
              pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
              message: '姓名不支持特殊字符',
              trigger: 'blur'
            }
          ],
          teacherId: [
            {required: true, message: '学号不能为空'},
            {validator: validTeacherId, trigger: 'blur'}
          ],
          studentId: [
            {required: true, message: '教师号不能为空'},
            {validator: validStudentId, trigger: 'blur'}
          ],
          college: [
            {required: true, message: '请输入学校', trigger: 'blur'},
            {
              required: true,
              pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
              message: '学校不支持特殊字符',
              trigger: 'blur'
            }
          ],
          school: [
            {required: true, message: '请输入名字', trigger: 'blur'},
            {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'},
            {
              required: true,
              pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
              message: '姓名不支持特殊字符',
              trigger: 'blur'
            }
          ],
          teacherCode: [
            {required: true, message: '验证码不能为空'},
            // {type: 'number', message: '输入正确的验证码'},
          ],
          studentCode: [
            {required: true, message: '验证码不能为空'},
            // {type: 'number', message: '输入正确的验证码'},
          ],
          StudentPassword: [
            {validator: validatePass3, trigger: 'blur'}
          ],
          StudentPassword2: [
            {validator: validatePass4, trigger: 'blur'}
          ],
        }
      };
    },
    created() {
      //this指的是当前的vue对象，把vue对象赋给_this
      const _this = this
      this.axios.get('http://localhost:8080/findAllAccount').then(function (resp) {
        //回调函数中的this指的是回调
        //把data数据赋给_this，即vue对象
        _this.accountAll = resp.data
      })
      this.axios.get('http://localhost:8080/findAllStudents').then(function (resp) {
        //回调函数中的this指的是回调
        //把data数据赋给_this，即vue对象
        _this.student = resp.data
      })
      this.axios.get('http://localhost:8080/getAllTeachers').then(function (resp) {
        //回调函数中的this指的是回调
        //把data数据赋给_this，即vue对象
        _this.teacher = resp.data
      })
      // this.getvCode();
    },
    mounted() {
      this.identifyTeacherCode = "";
      this.makeTeacherCode(this.identifyTeacherCodes, 4);
      this.identifyStudentCode = "";
      this.makeStudentCode(this.identifyStudentCodes, 4);
    },

    methods: {
      // getvCode() {
      //   this.s = "http://127.0.0.1:81/verifyCode";
      // },

      randomNum(min, max) {
        return Math.floor(Math.random() * (max - min) + min);
      },
      refreshTeacherCode() {
        this.identifyTeacherCode = "";
        this.makeTeacherCode(this.identifyTeacherCodes, 4);
      },
      makeTeacherCode(o, l) {
        for (let i = 0; i < l; i++) {
          this.identifyTeacherCode += this.identifyTeacherCodes[
            this.randomNum(0, this.identifyTeacherCodes.length)
            ];
        }
        console.log(this.identifyTeacherCode)
      },
      refreshStudentCode() {
        this.identifyStudentCode = "";
        this.makeStudentCode(this.identifyStudentCodes, 4);
      },
      makeStudentCode(o, l) {
        for (let i = 0; i < l; i++) {
          this.identifyStudentCode += this.identifyStudentCodes[
            this.randomNum(0, this.identifyStudentCodes.length)
            ];
        }
      },
      test(){
        console.log(this.isRepeat());
      },
      random() {
        this.r = Math.round(Math.random() * 1000000 + 100000);
      },
      turnstudent() {
        document.getElementById('registerbox').setAttribute('class', 'registerboxhide');
        document.getElementById('registerboxteacher').setAttribute('class', 'registerboxhide');
        document.getElementById('registerboxstudent').setAttribute('class', 'registerbox2');
      },
      turnteacher() {
        document.getElementById('registerbox').setAttribute('class', 'registerboxhide');
        document.getElementById('registerboxstudent').setAttribute('class', 'registerboxhide');
        document.getElementById('registerboxteacher').setAttribute('class', 'registerbox2');
      },
      turnbox() {
        document.getElementById('registerbox').setAttribute('class', 'registerbox');
        document.getElementById('registerboxstudent').setAttribute('class', 'registerboxhide');
        document.getElementById('registerboxteacher').setAttribute('class', 'registerboxhide');

      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.studentForm.studentCode!=this.identifyStudentCode){
              this.$message({
                message: '验证码错误',
                type: 'error'
              });
              this.refreshStudentCode();
            }else {
              this.studentForm.studentPassword = md5(this.studentForm.studentPassword)
              axios.post('http://localhost:8080/getStudentRegister', this.studentForm)
                .then((response) => {
                  this.$message({
                    message: '注册成功',
                    type: 'success'
                  });
                  this.$router.push("/login")
                })
                .catch(function (error) {
                  this.$message({
                    message: '注册失败,出现错误',
                    type: 'error'
                  });
                  this.$router.push("/login")
                });
            }
          } else {
            this.$message({
              message: '注册失败，表单不合法',
              type: 'error'
            });
            return false;
          }
        });

      },
      submitForm1(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.teacherForm.teacherCode!=this.identifyTeacherCode){
              this.$message({
                message: '验证码错误',
                type: 'error'
              });
              this.refreshTeacherCode();
            }else {
              this.teacherForm.teacherPassword = md5(this.teacherForm.teacherPassword)
              axios.post('http://localhost:8080/getTeacherRegister', this.teacherForm)
                .then((response) => {
                  this.$message({
                    message: '注册成功',
                    type: 'success'
                  });
                  this.$router.push("/login")
                })
                .catch(function (error) {
                  this.$message({
                    message: '注册失败,出现错误',
                    type: 'error'
                  });
                  this.$router.push("/login")
                });
            }
          } else {
            this.$message({
              message: '注册失败，表单不合法',
              type: 'error'
            });
            return false;
          }
        });
      },
    }
  }
</script>

<style scoped>
  .register {
    width: 1520px;
    height: 750px;
    background-image: url("https://www.ketangpai.com/Public/Home/img/reg-bg-01.jpg");
    position: relative;
  }

  .registerbox {
    width: 480px;
    height: 504px;
    background-color: white;
    position: absolute;
    top: 80px;
    left: 500px;
    text-align: left;
    padding: 30px;
  }

  .registerbox div {
    margin-top: 40px;
    width: 480px;
    height: 70px;
  }

  .registerbox a {
    text-decoration: none;
    color: #818181;
    float: right;
    margin-top: 30px;
    margin-right: 40px;
  }

  .registerbox2 {
    width: 440px;
    height: 554px;
    background-color: white;
    position: absolute;
    top: 80px;
    left: 500px;
    text-align: left;
    padding: 30px;
  }

  .el-form-item {
    margin-bottom: 16px;
  }

  .registerboxhide {
    display: none;
  }

  .el-form-item__error {
    right: 0px !important;
  }
</style>
<style>

  .el-input__inner {
    width: 100%;
    height: 40px !important;
    font-size: 20px;
  }

  a {
    text-decoration: none;
    color: #818181;
  }
  .code {
    width: 112px;
    height: 35px;
    border: 1px solid #ccc;
    float: right;
    border-radius: 2px;
  }
</style>

